package com.luo.d3s.core.infrastructure.convertor;

import com.luo.d3s.core.domain.model.ValueObjectEnum;
import com.luo.d3s.core.exception.SysException;

import javax.persistence.AttributeConverter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Optional;

/**
 * 基础JPA值对象枚举属性转换器
 *
 * @param <T> 值对象枚举类型
 * @param <D> 值对象枚举数据库类型
 * @author luohq
 * @date 2023-07-27
 */
public abstract class JpaVoEnumAttrConverter<T extends ValueObjectEnum<D>, D> implements AttributeConverter<T, D> {
    protected Class<T> voEnumClass;

    protected JpaVoEnumAttrConverter() {
        //提取第一个模板参数T的class类型
        Type genType = this.getClass().getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            throw new SysException("BaseJpaVoEnumAttrConverter init Exception - ", genType.getTypeName());
        }
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        this.voEnumClass = (Class<T>) params[0];
    }


    @Override
    public D convertToDatabaseColumn(T attribute) {
        return Optional.ofNullable(attribute)
                .map(ValueObjectEnum::getValue)
                .orElse(null);
    }

    @Override
    public T convertToEntityAttribute(D dbData) {
        return ValueObjectEnum.of(dbData, voEnumClass);
    }
}